package com.lepu.app.fun.chat.fragment;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.app.application.MyApplication;
import com.app.config.UserConfig;
import com.app.utils.Const;
import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.eyzhs.app.R;
import com.lepu.app.fun.chat.adapter.ChatSessionAdapter;
import com.lepu.app.fun.chat.bean.ChatSession;
import com.lepu.app.fun.chat.bean.Question;
import com.lepu.app.fun.chat.bean.QuestionDeadLine;
import com.lepu.app.fun.chat.bean.QuestionEntity;
import com.lepu.app.fun.chat.business.chatcore.ChatDAO;
import com.lepu.app.fun.chat.business.chatcore.ChatManager;
import com.lepu.app.fun.chat.business.chatcore.DoctorManager;
import com.lepu.app.fun.chat.controller.base.AbsBaseFragment;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.widget.CustomTopBarNew;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import org.json.JSONException;
import org.json.JSONObject;

import common.db.Constants;
import util.DateUtil;
import util.JSONUtils;

public class ChatSessionFragment extends AbsBaseFragment implements
        CustomTopBarNew.OnTopbarNewLeftLayoutListener {
    private static final String TAG = ChatSessionFragment.class.getSimpleName();
    private View mMainView = null;
    private boolean mInitDataSuccess = false;//  是否加载完数据
    private ListView listView;
    private List<ChatSession> chatSessionList = new ArrayList<ChatSession>();
    private ChatSessionAdapter chatSessionAdapter;
    private ImageLoader imageLoader;
    private LocalBroadcastManager broadcastManager;
    private TextView mTxtTip;
    private boolean mIsVisible;
    private static final int PAGESIZE = 1000;
    private int pageIndex = 1;
    private Object questList;
    private int mDeletePosition;
    private static final String REQUEST_DATA = "ChatSessionFragment_request_data";
    private static final String GETQUESTIONSTATUS = "ChatSessionFragment_getQuestionStatus";
    private static final String DELETEQUESTION = "ChatSessionFragment_deleteQuestion";
    /********************************/
    private static final int REQUEST_STATE = 200;
    private static final int REQUEST_DOCTORLIST = 1; //加载医生列表成功
    private static final int DELETE_SUCCESS = 201;//删除成功
    private int mCurrentPosition = 0;


    @SuppressLint("InflateParams")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMainView = LayoutInflater.from(getActivity()).inflate(R.layout.chat_fragment_chat_session, null, false);
        
        //topbar
        CustomTopBarNew topbar = (CustomTopBarNew) mMainView.findViewById(R.id.topbar);
        topbar.setTopbarTitle(R.string.chat_zixun_record);
        topbar.setonTopbarNewLeftLayoutListener(this);
        init();
        registerBroadcase();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        ViewGroup p = (ViewGroup) mMainView.getParent();
        if (p != null) {
            p.removeAllViewsInLayout();
        }
        return mMainView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mInitDataSuccess = false;
        if (broadcastManager != null) {
            broadcastManager.unregisterReceiver(receiver);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (!mIsVisible)
            return;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        getActivity().getMenuInflater().inflate(R.menu.menu_chat_session, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info =
                (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        mDeletePosition = info.position;
        ChatSession chatSession = (ChatSession) chatSessionAdapter.getItem(mDeletePosition);
        switch (item.getItemId()) {
            case R.id.action_single_delete:
                deleteItem(chatSession);
                return true;
            default:
                break;
        }
        return super.onContextItemSelected(item);
    }

    /**
     * 加载数据
     */
    private void feachData() {
        List<ChatSession> sessionList = ChatManager.getInstance().getChatSessions();
        feachList(sessionList);
    }

    private void feachList(List<ChatSession> sessionList) {
        if (sessionList != null && chatSessionAdapter != null) {
            if (sessionList.size() > 0) {
                chatSessionList.clear();
                mTxtTip.setVisibility(View.GONE);
                chatSessionList.addAll(sessionList);
                chatSessionAdapter.notifyDataSetChanged();
            } else if (sessionList.size() == 0) {
                isShowTips();
                chatSessionAdapter.clearAll();
                chatSessionAdapter.notifyDataSetChanged();
            }
        } else {
            if (mTxtTip != null)
                isShowTips();
        }
    }

    private void isShowTips() {
//        if (LoginUtil.checkIsLogin()) {
//            mTxtTip.setText(getText(R.string.not_data));
//        } else {
//            mTxtTip.setText(getText(R.string.not_data));
//        }
    }

    /**
     * 删除用户
     *
     * @param chatSession
     */
    private void deleteItem(ChatSession chatSession) {
        DoctorManager.getInstance().deleteQuestion(DELETEQUESTION, asyncRequest, chatSession.getQuestionID());
    }

    private void init() {
        chatSessionList = ChatManager.getInstance().getChatSessions();
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity()));
        listView = (ListView) mMainView.findViewById(R.id.lstView_chat_session);
        mTxtTip = (TextView) mMainView.findViewById(R.id.txt_tip);
        //mTxtTip.setOnClickListener(this);
        registerForContextMenu(listView);
        chatSessionAdapter = new ChatSessionAdapter(getActivity(), chatSessionList,
                ImageLoader.getInstance());
        listView.setAdapter(chatSessionAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                //**请求网络
                mCurrentPosition = i;
                String quesionId = chatSessionList.get(i).getQuestionID();
                DoctorManager.getInstance().getQuestionStatus(GETQUESTIONSTATUS, asyncRequest, quesionId);
            }
        });
        showBlankFile();
        setMessageHandle();
        //// TODO: 2015/12/11  没有记录进行查询
        if (chatSessionList == null || chatSessionList.size() == 0) {
            assert (LoginUtil.checkIsLogin());
            getQuestList();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!mIsVisible)
            return;
        try {
            if (mIsVisible) {
                LogUtilBase.LogD(TAG, "[chatting] setChatSession");
                updateTip();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setMessageHandle() {
        Handler h = new Handler() {
            public void handleMessage(Message msg) {
                if (msg == null) {
                    LogUtilBase.LogD(TAG, "handleMessage: msg is null");
                    return;
                }
                Bundle data = msg.getData();
                if (data == null) {
                    LogUtilBase.LogD(TAG, "handleMessage: data is null");
                    return;
                }
                ChatSession session = (ChatSession) data.getSerializable(Constants.Chat.CHAT_SESSION);
                if (session == null) {
                    LogUtilBase.LogD(TAG, "handleMessage: session is null for msg " + msg.what);
                    return;
                }
                switch (msg.what) {
                    case Constants.Chat.CHAT_MESSAGE_RECEIVED:
                        LogUtilBase.LogD(TAG, "Session List:CHAT_MESSAGE_RECEIVED");
                        boolean isNew = true;

                        for (int i = 0; i < chatSessionList.size(); i++) {
                            if (chatSessionList.get(i).getSessionId() == session.getSessionId()) {
                                chatSessionList.set(i, session);
                                isNew = false;
                                break;
                            }
                        }
                        if (isNew) {
                            //todo 直接显示出来一条新的记录
                            chatSessionList.add(session);
                        }
                        handleNewMessageCount(0);
                        //更新单个
                        TextView textviewTips = (TextView) listView.findViewWithTag(session.getQuestionID());

                        if (textviewTips != null) {
                            String couont = textviewTips.getText().toString();
                            int chessCount = Integer.valueOf(couont);
                            if (couont.equals("0") || TextUtils.isEmpty(couont)) {
                                chessCount = 1;
                            } else {
                                chessCount += 1;
                            }
                            textviewTips.setText(String.valueOf(chessCount));
                        }
                        if (textviewTips == null)
                            chatSessionAdapter.notifyDataSetChanged();
                        break;
                    case Constants.Chat.CHAT_MESSAGE_CHANGED:
                        LogUtilBase.LogD(TAG, "Chatting Room:CHAT_MESSAGE_CHANGED");
                        for (int i = 0, count = chatSessionList.size(); i < count; i++) {
                            if (chatSessionList == null || chatSessionList.get(i) == null ||
                                    TextUtils.isEmpty(chatSessionList.get(i).getLastMsgContent())) {
                                break;
                            }
                            if (chatSessionList.get(i).getSessionId() == session.getSessionId()) {
                                chatSessionList.set(i, session);
                                isNew = false;
                                break;
                            }
                        }
                        handleNewMessageCount(0);

                        if (chatSessionAdapter != null) {
                            chatSessionAdapter.notifyDataSetChanged();
                        }
                        break;
                    default:
                        break;
                }
            }
        };
        MyApplication.getInstance().setChatSessionHandler(h);
    }


    /**
     * 设置null 的填充
     */
    private void showBlankFile() {
        if (mTxtTip == null || !isAdded()) {
            return;
        }
        isShowTips();
        if (chatSessionList != null && chatSessionList.size() > 0) {
            //隐藏
            mTxtTip.setVisibility(View.GONE);
        } else if (chatSessionList == null || chatSessionList.size() == 0) {
            //显示
            mTxtTip.setVisibility(View.VISIBLE);
        }
    }

    private void handleNewMessageCount(int noticeCount) {
        int count = noticeCount;
        for (int i = 0; i < chatSessionList.size(); i++) {
            if (chatSessionList.get(i).getLastMsgContent().equals(Constants.Counts.NEW_PATIENT_FLAG)) {
                count = count + 1;
            } else {
                count = count + chatSessionList.get(i).getNewMsgCount();
            }
        }
        // showBlankFile();
    }

    /**
     * 注册广播
     */
    private void registerBroadcase() {
        broadcastManager = LocalBroadcastManager.getInstance(getActivity());
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.FILTER_ACTION_TO_CHAT_SESSIION);
        broadcastManager.registerReceiver(receiver, filter);
    }

    /**
     * 处理广播
     */
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (isAdded()) {
                updateTip();
            }
        }
    };

    private void updateTip() {
        List<ChatSession> sessions = ChatDAO.getInstance().
                getChatSessions();
        if (sessions == null) {
            LogUtilBase.LogD(TAG, "session or sessions is  NULL");
            return;
        }
        feachList(sessions);
    }

    @Override
    public void onTopbarLeftLayoutSelected() {
        //更新数量
        onkeydown();
    }

    /**
     * 跳转到聊天界面
     *
     * @param questionDeadLine
     */
    private void gotoChatingFragment(QuestionDeadLine questionDeadLine) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(Constants.Chat.CHAT_SESSION, chatSessionList.get(mCurrentPosition));
        bundle.putSerializable(Const.QUESTIONDEADLINE, questionDeadLine);
        bundle.putBoolean("from_history", true);
        performGoAction("gotoChattingFragment", bundle);
    }

/****************************************************/
    /**
     * 获取问题列表
     */
    public void getQuestList() {
        String request = REQUEST_DATA;
        DoctorManager.getInstance().getConsultQuestionList(request, asyncRequest, pageIndex, PAGESIZE);
    }

    AsyncRequest asyncRequest = new AsyncRequest() {
        @Override
        public void RequestComplete(Object o, Object o1) {
            if (o.equals(REQUEST_DATA)) {//请求医生列表
                QuestionEntity questionEntities = QuestionEntity.parseJsonData((String) o1);

                if (questionEntities != null && questionEntities.questions.size() > 0) {
                    chatSessionList.clear();
                    for (Question question : questionEntities.questions) {
                        ChatSession chatSession = new ChatSession();
                        chatSession.setUserId(Long.valueOf(question.DoctorID));
                        chatSession.setQuestionID(question.QuestionID);
                        chatSession.setUserNickName(question.DoctorName);
                        chatSession.setUserProfilePictureId(question.Avatar);
                        chatSession.setQuestion(question.Question);
                        chatSession.setHostUserId(Long.valueOf(LoginUtil.getUserId()));
                        chatSession.setLastMsgContent(question.Question);
                        chatSession.setLastMsgTime(
                                DateUtil.dateFromString(question.RecordCreateTime, DateUtil.CALENDAR_ALL));
                        chatSessionList.add(chatSession);
                    }
                }
                sendToMainUi(null, REQUEST_DOCTORLIST);

                //插入数据库
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (ChatSession chatSession : chatSessionList) {

                            ChatDAO.getInstance().insertChatSession(chatSession);
                        }
                    }
                }).start();

            } else if (o.equals(GETQUESTIONSTATUS)) { //获取医生问题状态
                try {
                    JSONObject jsonObject = new JSONObject((String) o1);
                    JSONObject jsonObject1 = jsonObject.optJSONObject("Result").optJSONObject("DetailInfo");
                    QuestionDeadLine questionDeadLine = JSONUtils.json2Bean(jsonObject1.toString(), QuestionDeadLine.class);
                    sendToMainUi(questionDeadLine, REQUEST_STATE);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (o.equals(DELETEQUESTION)) {//删除列表
                //todo 删除成功
                sendToMainUi(null, DELETE_SUCCESS);
            }
        }

        @Override
        public void RequestError(Object o, int i, final String s) {
            assert (getActivity() != null);
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    assert (s != null && !TextUtils.isEmpty(s));
                    showErrorMessage(s);
                }
            });
        }
    };

    /**
     * 显示错误信息
     *
     * @param s
     */
    private void showErrorMessage(String s) {
        try {
            JSONObject jsonObject = new JSONObject(s);
            String messageError = jsonObject.optJSONObject("Result").optString("Message");
            UIHelper.showToast(getActivity(), messageError);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REQUEST_STATE: //获取过期状态
                    QuestionDeadLine questionDeadLine = (QuestionDeadLine) msg.obj;
                    //进行跳转展示
                    gotoChatingFragment(questionDeadLine);
                    break;
                case REQUEST_DOCTORLIST:
                    showBlankFile();
                    chatSessionAdapter.notifyDataSetChanged();
                    break;
                case DELETE_SUCCESS:
                    ChatSession chatSession = chatSessionList.get(mDeletePosition);
                    chatSessionList.remove(chatSession);
                    chatSessionAdapter.notifyDataSetChanged();
                    ChatDAO.getInstance().deleteChatSessionDoctor(String.valueOf(chatSession.getHostUserId())
                            , String.valueOf(chatSession.getQuestionID()));
                    ObserverManager.getInstance().notify(ObserverConst.NOTIFY_ZXRECORDER_CHANGE, null, null);
                    showBlankFile();
                    // updateTip();
                    break;
                default:
                    break;
            }
        }
    };

    private void sendToMainUi(Object questionID, int type) {
        Message message = Message.obtain();
        message.obj = questionID;
        message.what = type;
        mHandler.sendMessage(message);
    }


    private void onkeydown() {
        showGuideView();
        ObserverManager.getInstance().notify(ObserverConst.NOTIFY_ZXRECORDER_CHANGE, null, null);
        performBack();
    }

    /**
     * 首次展示引导页面
     */
    private void showGuideView() {
        boolean isGuide = UserConfig.getConfigBoolean(getActivity(), Const.ISQUESTIONGUID, false);
        if (!isGuide && MainTabActivity.getInstance() != null) {
            //没有引导过
            final LinearLayout linearLayout = (LinearLayout) MainTabActivity.getInstance().findViewById(R.id.line_guide);
            linearLayout.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return true;
                }
            });
            linearLayout.setVisibility(View.VISIBLE);
            ImageView imageView = (ImageView) MainTabActivity.getInstance().findViewById(R.id.imgview_close);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    linearLayout.setVisibility(View.GONE);
                    UserConfig.setConfig(MainTabActivity.getInstance(), Const.ISQUESTIONGUID, true);
                }
            });
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        onkeydown();
        return super.onKeyDown(keyCode, event);
    }


}
